package Server.ExtComponents.socket;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.*;

import static org.jboss.netty.channel.Channels.write;

/**
 *  * @author :石头哥哥<br/>
 *         Project:CreazyGameServer1.6
 *         Date: 13-3-29
 *         Time: 上午11:15
    //@ChannelHandler.Sharable
    //public final class MServerFrameEncoder extends OneToOneEncoder {
    //    @Override
    //    protected Object encode(
    //            ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
    //        if (!(msg instanceof ChannelBuffer))return null;  //because  it's must be channelBuffer
    //        return msg;
    //    }
    //
    //}
 *  // Decoders
 * pipeline.addLast("frameDecoder", new {@link org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder}(80, {@link org.jboss.netty.handler.codec.frame.Delimiters#nulDelimiter()}));
 * pipeline.addLast("base64Decoder", new {@link org.jboss.netty.handler.codec.base64.Base64Decoder}());
 *
 * // Encoder
 * pipeline.addLast("base64Encoder", new {@link org.jboss.netty.handler.codec.base64.Base64Encoder}());
 *
 */
@ChannelHandler.Sharable
public final class MServerFrameEncoder implements ChannelDownstreamHandler {


    protected MServerFrameEncoder(){
    }
    /**
     * Handles the specified downstream event.
     *
     * @param ctx the context object for this handler
     * @param evt   the downstream event to process or intercept
     */
    @Override
    public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
        if (!(evt instanceof MessageEvent)) {
            ctx.sendDownstream(evt);
            return;
        }
        MessageEvent e = (MessageEvent) evt;
        if (!doEncode(ctx, e)) {
            ctx.sendDownstream(e);
        }
    }
    private boolean doEncode(ChannelHandlerContext ctx, MessageEvent e) throws Exception{
        Object message=e.getMessage();
        if (!( message instanceof ChannelBuffer)|| message==null)return false;
        write(ctx, e.getFuture(), message, e.getRemoteAddress());
        return true;
    }
}
